package com.dimpt.unigw.token;

import com.dycs.entity.UserToken;

import java.security.*;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.crypto.Data;


public class TokenService {


    private static final String ALGORITHM = "AES";
    private static final String ENCODING = "UTF-8";
    private static final String SECRET_KEY = "ansfiehhaknva908safaf99af79a0f7q";

    public static UserToken generateTokenWithUsernameAndPassword(String username, String password) {

        return createToken(username,password);
    }

    public static UserToken generateTokenWithUserKeys(String publicKey, String privateKey) {

        return createToken(publicKey,privateKey);
    }

    private static UserToken createToken(String str1, String str2) {

        if (isValid(str1,str2)) {
            return null;
        }

        try {
            String tokenData = str1 + ":" + str2;
            byte[] encryptedData = encrypt(tokenData.getBytes(ENCODING));
            String token = Base64.getEncoder().encodeToString(encryptedData);
            long nowMills = System.currentTimeMillis();
            int status = 1;
            Timestamp createTime = new Timestamp(nowMills);
            Timestamp expiredTime = new Timestamp(nowMills + 60 * 60 * 1000);
            UserToken userToken = new UserToken();
            userToken.setToken(token);
            userToken.setExpiredtime(expiredTime);
            userToken.setCreatetime(createTime);
            userToken.setStatus(status);
            return userToken;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static byte[] encrypt(byte[] data) {
        try {
            Key key = generateKey();
            Cipher c = Cipher.getInstance(ALGORITHM);
            c.init(Cipher.ENCRYPT_MODE, key);
            return c.doFinal(data);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static boolean isValid(String str1, String str2) {
        return str1 == null || str1 == "" || str2 == null || str2 == "";
    }

    private static Key generateKey() {
        return new SecretKeySpec(SECRET_KEY.getBytes(), ALGORITHM);
    }

    public static String decrypt(byte[] encrypted) {
        try {
            Key key = generateKey();
            Cipher c = Cipher.getInstance(ALGORITHM);
            c.init(Cipher.DECRYPT_MODE, key);
            byte[] decrypted = c.doFinal(encrypted);
            return new String(decrypted, ENCODING);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String decryptToken(String encryptedToken) {
        try {
            byte[] decodedToken = Base64.getDecoder().decode(encryptedToken);
            return decrypt(decodedToken);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String getUid(String token) {

        String tokenData = decryptToken(token);
        int i = tokenData.indexOf(':');
        return tokenData.substring(0, i);
    }
}

//    private static final String SECRET_KEY = "ansfiehhaknva9879asljffefalkns08safaf99af79a0f7q";
//
//
//    // 生成密钥对
//    public static KeyPair generateKeyPair() throws Exception {
//        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
//        keyPairGenerator.initialize(2048); // 设置密钥长度为2048位
//        return keyPairGenerator.generateKeyPair();
//    }
//
//    // 生成token
//    public static String generateToken(String username, String password) {
//        return createToken(username + ":" + password);
//    }
//
//    // 创建token
//    private static String createToken(String subject) {
//        SignatureAlgorithm algorithm = SignatureAlgorithm.HS256;
//        long nowMillis = System.currentTimeMillis();
//        Key signingKey = generateKey();
//
//        JwtBuilder builder = Jwts.builder()
//                .setIssuedAt(new Date(nowMillis))
//                .setExpiration(new Date(nowMillis + 60 * 60 * 1000))
//                .setSubject(subject)
//                .signWith(algorithm, signingKey);
//
//        return builder.compact();
//    }
//
//    // 创建token
//    public static String createToken(String subject, PrivateKey privateKey) {
//        SignatureAlgorithm algorithm = SignatureAlgorithm.RS256;
//        long nowMillis = System.currentTimeMillis();
//
//        JwtBuilder builder = Jwts.builder()
//                .setIssuedAt(new Date(nowMillis))
//                .setExpiration(new Date(nowMillis + 60 * 60 * 1000))
//                .setSubject(subject)
//                .signWith(algorithm, privateKey);
//
//        return builder.compact();
//    }
//
//    // 解析token
//    public static String parseToken(String token) {
//
//        try {
//            Claims claims = Jwts.parserBuilder()
//                    .setSigningKey(generateKey())
//                    .build()
//                    .parseClaimsJws(token)
//                    .getBody();
//
//            return claims.getSubject();
//        } catch (JwtException e) {
//            return null;
//        }
//
//    }
//
//    // 解析token
//    public static String parseToken(String token, PublicKey publicKey) {
//
//        try {
//            Claims claims = Jwts.parserBuilder()
//                    .setSigningKey(publicKey)
//                    .build()
//                    .parseClaimsJws(token)
//                    .getBody();
//
//            return claims.getSubject();
//        } catch (JwtException e) {
//            return null;
//        }
//    }
//
//    // 生成密钥
//    private static Key generateKey() {
//        byte[] decodedKey = Base64.getMimeDecoder().decode(SECRET_KEY);
//        return new SecretKeySpec(decodedKey, 0, decodedKey.length, "HmacSHA256");
//    }